const { ipcMain, Notification } = require('electron');
const config = require('./config');
const { Ipc } = require('./utils');

const { GLOBAL_APP_ID } = config;

class notifications {
    constructor() {
        this.notifications = [];
        this.initIpc();
    }

    initIpc() {
        ipcMain.on('notifications-to', (event, args) => {
            this.update(args || []);
        });
    }

    /**
     * 
     * @param {*} notifications 
     */
    update(notifications) {
        notifications.sort((i, j) => i.time - j.time);
        this.notifications = notifications;
        this.startLoop();
    }

    startLoop() {
        this.loop();
        this.stopLoop();
        const timeout = parseInt(process.env.KOOLEARN_NOTIFICATION_LOOP_TIME || `${1000 * 30}`);
        this.timer = setInterval(this.loop.bind(this), timeout);
    }

    stopLoop() {
        if (this.timer) {
            clearInterval(this.timer);
            this.timer = null;
        }
    }

    loop() {
        if (!this.notifications || this.notifications.length <= 0) {
            this.stopLoop();
            return;
        }

        const notification = this.notifications[0];
        if (notification.time >= Date.now()) {
            return;
        }

        this.notifications.shift();

        this.show(notification);
    }

    show(notification) {
        const n = new Notification({
            title: notification.title,
            body: notification.body,
        });

        n.on('click', () => {
            console.log('notification click');
            if (global.mainWindow) {
                Ipc.send('notification-click', notification);
            } else {
                this.createWindow && this.createWindow();
            }
        });

        n.show();
    }
}

module.exports = notifications;